package pers.ree.demo.concurrent;

import java.util.concurrent.TimeUnit;

public class DaemonDemo {

    public static void main(String[] args) {

        DaemonDemo daemonDemo = new DaemonDemo();

//        daemonDemo.test1();

        // 没有将子线程设置为守护线程
        // 即使主线程执行完了，子线程还是会一直执行下去
//        daemonDemo.test2();

        // 将子线程设置为守护线程
        // 主线程执行完毕，子线程也结束了
        daemonDemo.test3();
    }

    public void test1() {
        Thread t = new Thread();
        System.out.println(t.isDaemon());
        t.setDaemon(true);
        System.out.println(t.isDaemon());
        t.start();
        System.out.println(t.isDaemon());
        try {
            // 此处会报错，线程start后，不允许再设置daemon
            t.setDaemon(false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(t.isDaemon());
    }

    private Thread getChildThread() {
        Thread childThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("I'm child thread");
                    try {
                        TimeUnit.MILLISECONDS.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });

        return childThread;
    }

    public void test2() {
        Thread childThread = getChildThread();
        childThread.start();
        System.out.println("I'm main thread");
    }

    public void test3() {
        Thread childThread = getChildThread();
        childThread.setDaemon(true);
        childThread.start();
        System.out.println("I'm main thread");
        for (int i=0; i<100; i++) {
            System.out.println(i);
            System.out.println("childThread isAlive: " + childThread.isAlive() + ", isDaemon: " + childThread.isDaemon());
            try {
                TimeUnit.MILLISECONDS.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Main thread end");
    }
}
